package com.yadong.smarthome2.devicefinder;


import java.util.HashMap;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.yadong.smarthome2.device.Device;
import com.yadong.smarthome2.device.Device.DeviceConnectionType;
import com.yadong.smarthome2.protocol2.ALog;

public class BluetoothDeviceFinder implements DeviceFinder {
    private Context mContext;
    private DeviceListener mDeviceListener;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean mDeviceDiscoverStarted;
    public static final HashMap<Device, BluetoothDevice> BLUETOOT_DEVICES =
            new HashMap<Device, BluetoothDevice>();

    public void setContext(Context context) {
        this.mContext = context;
    }

    @Override
    public boolean scanDevice(DeviceListener listener) {
        ALog.logd(this, "start scan bluetooth device");
        BLUETOOT_DEVICES.clear();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mDeviceDiscoverStarted = mBluetoothAdapter.startDiscovery();
        mDeviceListener = listener;
        if (mDeviceDiscoverStarted) {
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            mContext.registerReceiver(mReceiver, filter);
        }
        return mDeviceDiscoverStarted;
    }

    // Create a BroadcastReceiver for ACTION_FOUND
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Device device2 = new Device(DeviceConnectionType.BLUETOOTH, device.getAddress(),
                        device.getName(), device.getAddress());
                BLUETOOT_DEVICES.put(device2, device);
                if (mDeviceListener != null) {
                    mDeviceListener.onDeviceFinded(device2);
                }
            }
        }
    };

    @Override
    public boolean stopScan() {
        ALog.logd(this, "stop scan bluetooth device");
        if (mDeviceDiscoverStarted) {
            mContext.unregisterReceiver(mReceiver);
        }
        return mBluetoothAdapter.cancelDiscovery();
    }

}
